//
//  LYRemotePeer.swift
//  RxSwift_Practice
//
//  Created by 李永彬 on 2020/4/28.
//  Copyright © 2020 李永彬. All rights reserved.
//

import Foundation

public protocol LYRemotePeerDelegate: class {
    /**
     Called when the remote peer sent data.
     - parameter remotePeripheral: The remote peripheral that sent the data.
     - parameter data: The data it sent.
     */
    func remotePeer(_ remotePeer: LYRemotePeer, didSendArbitraryData data: Data)
}

public func == (lhs: LYRemotePeer, rhs: LYRemotePeer) -> Bool {
    return (lhs.identifier == rhs.identifier)
}

public class LYRemotePeer: Equatable {

    /// A unique identifier for the peer, derived from the underlying CBCentral or CBPeripheral object, or set manually.
    public let identifier: UUID

    public weak var delegate: LYRemotePeerDelegate?

    internal var configuration: LYConfiguration?
    private var data: Data?

    init(identifier: UUID) {
        self.identifier = identifier
    }

    internal var maximumUpdateValueLength: Int {
        return 20
    }

    internal func handleReceivedData(_ receivedData: Data) {
        if receivedData == configuration!.endOfDataMark {
            if let finalData = data {
                delegate?.remotePeer(self, didSendArbitraryData: finalData)
            }
            data = nil
            return
        }
        if self.data != nil {
            self.data?.append(receivedData)
            return
        }
        self.data = receivedData
    }
}
